package com.student91.recruit.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;

@Controller
@Slf4j
public class FileUploadController {

    // 访问路径为：http://ip:port/upload
    @RequestMapping(value = "/excelFile", method = RequestMethod.GET)
    public String upload() {
        return "/excelFile";
    }

    @RequestMapping(value = "/excelFile", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestParam("excelFile") MultipartFile file, HttpServletRequest request) {
//        String path=request.getSession().getServletContext().getRealPath("/files/");
        String path="D:/1-LJ-idea/files";
        log.info(path);
        String fileName=new Date().getTime()
                + "." + file.getOriginalFilename().substring(file.getOriginalFilename().indexOf('.') + 1, file.getOriginalFilename().length());
        if (!file.isEmpty()) {
            try {
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(new File(path+fileName)));
                out.write(file.getBytes());
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return "notFound";
            } catch (IOException e) {
                e.printStackTrace();
                return "fail";
            }
//            throw new RuntimeException("上传成功!");
            return "success";
        } else {
//            throw new RuntimeException("上传失败，因为文件是空的");
            return "isNull";
        }
    }
}
